package com.ccl.iot.views;import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Scroller;

import com.ccl.iot.publics.Debugger;

public class RefreshableView extends LinearLayout {
	private Scroller iScroller = null;
	
	private LinearLayout iRefreshView = null;
	private int iLastDragY = 0;
	
	public RefreshableView(Context context) {
		super(context);
		
		initialize();
	}
	
	private void initialize(){
		iScroller = new Scroller(this.getContext());
		
		iRefreshView = new LinearLayout(this.getContext());
		iRefreshView.setBackgroundColor(Color.RED);
		
		LayoutParams tLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 50);
		tLayoutParams.topMargin = -50;
		tLayoutParams.gravity = Gravity.CENTER;
		
		this.addView(iRefreshView, tLayoutParams);
	}
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent event) {
		if (event != null){
			int tY = (int) event.getY();
			
			//Debugger.Print(event.getAction());
			switch (event.getAction()){
				case MotionEvent.ACTION_DOWN:{
					iLastDragY = tY;
					
					break;
				}
				case MotionEvent.ACTION_MOVE:{
					int tMove = tY - iLastDragY;
					
					Debugger.Print("Move " + tMove);
					
					
					
					break;
				}
				case MotionEvent.ACTION_UP:{
					
					break;
				}
			}
		}
		
		return super.onInterceptTouchEvent(event);
	}
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
       
		int tCount = this.getChildCount();
    	
        for (int i = 0; i < tCount; i++) {
        	View tView = this.getChildAt(i);
        	
        	if (tView.equals(iRefreshView)){
        		tView.layout(l, t - 50, r, t);
        	}else{
         		tView.layout(l, t, r, b);       		
        	}
        }
        
        Debugger.Print("Layout " + l + "," + t + "," + r + "," + b);
	}

	@Override
	public void computeScroll() {
		if (iScroller.computeScrollOffset()){
			int tY = iScroller.getCurrY();
			
			LayoutParams tLayoutParams = (LayoutParams) iRefreshView.getLayoutParams();
			tLayoutParams.topMargin = Math.max(tY, -50);
			
			iRefreshView.setLayoutParams(tLayoutParams);
			iRefreshView.invalidate();
			this.invalidate();
		}
	}
}
